import { useEffect, useRef } from 'react'
import { CustomPlayer } from '@/utils/rtcPlayer.utls'
import styles from './index.module.css'

let rtcPlayer: CustomPlayer | null = null;

const RtcPlayer = ({ url }: { url: string }) => {
    const playerWrapperRef = useRef(null);

    useEffect(() => {
        if (rtcPlayer) {
            rtcPlayer.close();
        }

        if (playerWrapperRef.current) {
            rtcPlayer = new CustomPlayer(url, playerWrapperRef.current);
            rtcPlayer.play();
        }

        return () => rtcPlayer?.close();
    }, [playerWrapperRef])

    return (
        <video className={styles.playerWrapper} autoPlay ref={playerWrapperRef}>
            Your browser is too old which doesn&apos;t support HTML5 video.
        </video>
    )
}

export default RtcPlayer